package com.example.websocket.websocket.socket;

import javafx.print.Collation;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.*;

public class SelectorService {

    static int cnum = 100;

    static final Object object = new Object();

    static Map<String, SocketChannel> map = new HashMap<>();

    static final String name = "test";

    public static void main(String[] args) {
        open();
    }

    public static void open() {
        try {
            Selector selector = Selector.open();

            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

            serverSocketChannel.socket().bind(new InetSocketAddress(8081));

            serverSocketChannel.configureBlocking(false);

            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            int sum = 1;
            while (true) {
                int readyChannels = selector.select();
                if (readyChannels == 0) {
                    return;
                }

                Set<SelectionKey> readyKey = selector.selectedKeys();
                Iterator<SelectionKey> iterator = readyKey.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    if (key.isAcceptable()) {
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector, SelectionKey.OP_READ);
                        map.put(name + sum, socketChannel);
                        sum++;
                    } else if (key.isReadable()) {
                        SocketChannel socketChannel = (SocketChannel) key.channel();
                        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                        int num = socketChannel.read(readBuffer);
                        if (num > 0) {
                            String content = new String(readBuffer.array());
                            String thisName = content.substring(0, content.indexOf(":"));
                            System.out.println("收到数据：" + content.trim());
                            ByteBuffer buffer;
                            if (cnum > 0) {
//                                buffer = ByteBuffer.wrap("返回给客户端的数据...购买成功".getBytes());
                                sendMsg(thisName);
                            } else {
                                buffer = ByteBuffer.wrap("返回给客户端的数据...库存不足".getBytes());
                                socketChannel.write(buffer);
                            }
                            updateNum();
                        } else if (num == -1) {
                            socketChannel.close();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void sendMsg(String thisName) throws IOException {
        synchronized (object) {
            ByteBuffer buffer;
            Set<String> names = map.keySet();
            names.remove(thisName);
//                                buffer = ByteBuffer.wrap(Integer.toString(cnum).getBytes());
            for (String sendName : names) {
                String sendContent = sendName + ":" + thisName + "购买了一件商品";
                buffer = ByteBuffer.wrap(sendContent.getBytes());
                SocketChannel sc = map.get(sendName);
                sc.write(buffer);
            }
        }
    }

    public static void updateNum() {
        synchronized (object) {
            if (cnum > 0) {
                cnum--;
            }
        }
    }

    public static int getNum() {
        synchronized (object) {
            System.out.println(cnum);
            return cnum;
        }
    }

}
